﻿using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Xml;

namespace TransactionServer.CRMPlugin.CRM
{
    public class Entity_ : Dictionary<string, object>, IXmlSerializable
    {
        public string System;
        public string Name;
        public string Id;

        public Entity_() { }

        public Entity_(string System, string Name, string Id)
        {
            this.System = System;
            this.Name = Name;
            this.Id = Id;
        }

        public Entity_(string System, string Name)
        {
            this.System = System;
            this.Name = Name;
        }

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(String));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(Object));

            System = reader.GetAttribute("System");
            Name = reader.GetAttribute("Name");
            Id = reader.GetAttribute("Id");

            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();

            if (wasEmpty)
                return;

            while (reader.NodeType != XmlNodeType.EndElement)
            {
                reader.ReadStartElement("item");

                reader.ReadStartElement("key");
                String key = (String)keySerializer.Deserialize(reader);
                reader.ReadEndElement();

                reader.ReadStartElement("value");
                Object value = (Object)valueSerializer.Deserialize(reader);
                reader.ReadEndElement();

                this.Add(key, value);

                reader.ReadEndElement();
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(String));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(Object));

            writer.WriteAttributeString("System", System);
            writer.WriteAttributeString("Name", Name);
            writer.WriteAttributeString("Id", Id);


            foreach (String key in this.Keys)
            {
                writer.WriteStartElement("item");

                writer.WriteStartElement("key");
                keySerializer.Serialize(writer, key);
                writer.WriteEndElement();

                writer.WriteStartElement("value");
                Object value = this[key];
                valueSerializer.Serialize(writer, value);
                writer.WriteEndElement();

                writer.WriteEndElement();
            }
        }
    }
}
